package com.swang.pms.service.manage.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.swang.pms.model.entity.PlfLog;
import com.swang.pms.service.manage.ManageLogService;

@Component("logFactory")
public class LogFactory {

    private static final Logger         logger  = Logger.getLogger(LogFactory.class);

    @Resource
    private ManageLogService            manageLogService;

    private final BlockingQueue<PlfLog> PlfLogs = new LinkedBlockingQueue<PlfLog>();

    public void addLog(PlfLog PlfLog) {
        try {
            PlfLogs.put(PlfLog);
        } catch (InterruptedException e) {
            logger.error("addLog error", e);
        }
    }

    @Scheduled(fixedDelay = 10000)
    public void saveLogs() {
        if (PlfLogs.size() <= 0) {
            return;
        }
        List<PlfLog> PlfLogList = new ArrayList<PlfLog>();
        try {
            PlfLog onePlfLog = PlfLogs.poll();
            while (onePlfLog != null) {
                PlfLogList.add(onePlfLog);
                onePlfLog = PlfLogs.poll();
            }
            this.manageLogService.batchInsert(PlfLogList);
        } catch (Exception e) {
            logger.error("saveLogs error", e);
        }
    }

}
